package com.yootoo.extpmml.smg3;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.yootoo.extpmml.Entites.model.ModelDesc;
import com.yootoo.extpmml.smg3.base.DataArea;
import com.yootoo.extpmml.smg3.base.RuleEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DynamicStrategiesRunner implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(DynamicStrategiesRunner.class);
    private String alias;
    private String signature;
    private Integer logLevel;

    public DynamicStrategiesRunner(ModelDesc strategy){
        Map properties = JSON.parseObject(strategy.getExtension(), HashMap.class);
        alias = String.valueOf(properties.get("alias"));
        signature = String.valueOf(properties.get("signature"));
        logLevel = Integer.valueOf(properties.getOrDefault("logLevel",0).toString());
        Smg3Cache.cache.put(alias,strategy);
    }

    /**
     * run Strategies logic
     * 参数传递给策略逻辑并执行输出结果
     *
     * @param m
     */
    public Map runStrategies(Map m) throws IOException {
        Preconditions.checkNotNull(alias);
        Preconditions.checkNotNull(signature);
        DataArea ctrlArea = new DataArea("OCONTROL");
        ctrlArea.setValue("ALIAS", alias);
        ctrlArea.setValue("SIGNATURE", signature);

        DataArea inArea = new DataArea("OINPUT");
        DataArea outArea = new DataArea("OOUTPUT");

        Iterator it = m.keySet().iterator();
        //将参数传递给策略
        while (it.hasNext()) {
            String key = it.next().toString();
            inArea.setValue(key, m.get(key));
        }
        //执行规则
        int code = RuleEngine.executeRule(logLevel, ctrlArea, inArea, outArea);
        logger.debug(code +"");
        return outArea.getArea();
    }
}
